package com.zhiqian.service.impl;

import com.zhiqian.enums.RpcError;
import com.zhiqian.exception.RpcException;
import com.zhiqian.service.ServiceProvider;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class DefaultServiceProvider implements ServiceProvider {
    //容器的键为注册服务的类实现的接口名称，值为这个类
    private static final Map<String,Object> serviceMap=new ConcurrentHashMap<>();
    //用于存放注册服务的类的名称
    private static final Set<String> registryService=ConcurrentHashMap.newKeySet();

    @Override
    public <T> void register(T service) {
        //获取注册服务的类的类名
        String serviceName = service.getClass().getCanonicalName();
        if (registryService.contains(serviceName)) return;
        registryService.add(serviceName);
        Class<?>[] interfaces = service.getClass().getInterfaces();
        if (interfaces.length==0){
            throw new RpcException(RpcError.SERVICE_NOT_IMPLEMENT_ANY_INTERFACE.getMessage());
        }
        for (Class<?> i:interfaces){
            serviceMap.put(i.getCanonicalName(),service);
        }
        log.info("向接口：{} 注册服务：{}",interfaces,serviceName);
    }

    @Override
    public Object getService(String serviceName) {
        Object service = serviceMap.get(serviceName);
        if (service==null){
            throw new RpcException(RpcError.SERVICE_NOT_FOUND.getMessage());
        }
        return service;
    }
}
